/**
 * WidgetEventVideoInput
 */

import React,{Component} from "react";
import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import editorActions from '../../../actions/Editor/editor';
import consts from "../../../utils/consts";
import storage from "../../../utils/storage";
import CommonProperty from "./CommonProperty";
import Upload from "../../../utils/upload/Upload";
import Validator from "../../../utils/validator/Validator";
import SingleUpload from "../../../utils/upload/SingleUpload";
class WidgetEventVideoInput extends Component {
    mixins: [CommonProperty]
    constructor(props) {
        super(props);
        this.state = {             
            currentTab: "local",
            uploading: false,
            upload: {
                html: null,
                title: null,
                percent: null
            },
            form: {
                model:{
                    md5: null,
                    url: null,
                    html: null,
                    label: null
                }
            },
            is_valid_video_src: true,
            errors: ''
        };
    }
    getInitialProps(){
        return {
            root: {},
            widget: {}
        }
    }
    componentDidMount(){
        this.initCurrentTab();
        let defaultSettings = {
            upload_url: storage.data.CONST.upload_url,
            md5Field: "music_md5",
            accept: "video/mp4",
            size: 50000000,
            placeholder: "请填写在线视频地址或者上传mp4格式文件",
            isIos: false,
            isAndroid: false,
            isZip: false,
            isAudio: false,
            isVideo: true
        };

        let target = $(this.refs.uploadGroup);
        this.helper = new SingleUpload(target, this, defaultSettings);
    }
    initCurrentTab(){
        const {widget} = this.props, {action} = widget;
        if(action && !action.md5 && action.html){
            this.setState({currentTab: 'web'})
        }
    }
    handleOnChangeVideoType(e){
        let element = $(e.target || e.srcElement);
        let type = element.attr("name");
        const {widget} = this.props;
        this.setState({
            currentTab: type
        });
        if(type == 'web' && widget.action.md5){
            delete widget.action.html
        }
    }
    handleOnHtmlChanged(e){
        const {widget,updateWidget,setState} = this.props;
        let element = $(e.target || e.srcElement);
        let html = element.val();
        let data = widget;
        this.handleOnChangeVideoSrc();
        data.action = $.extend(true, {}, widget.action, {html: html});
        delete data.action.md5;
        delete data.action.url;

        this.storeData = data;
        setState({selectedWidget: data});
        updateWidget(data);
    }
    handleOnInputBlur(){
        const {updateWidget,setState} = this.props;
        if (this.storeData && this.state.is_valid_video_src){
            setState({selectedWidget: this.storeData});
            updateWidget(this.storeData);
        }
    }
    handleOnChangeVideoSrc(){
        let validator = Validator();

        validator.addRule($(this.refs.htmlInput), [{
            validator: "empty",
            error: $._('Video url required')
        }]);

        validator.addRule($(this.refs.htmlInput), [{
            validator: "video",
            error: $._('Video url error')
        }]);

        let errors = validator.execute();
        this.setState({
            is_valid_video_src: !errors,
            errors: errors
        });
        let src = $(this.refs.htmlInput).val();
    }
    handleOnStartUpload(){
        this.helper.startUpload();
    }
    handleOnCancelUpload(){
        this.helper.cancelUpload();
    }
    updateUploaded(uploaded){
        this.setState({ fileUploaded: uploaded });
    }
    render(){
        const {widget} = this.props;
        let currentTab = this.state.currentTab;

        let html = widget.action.html || "";
        let label = widget.action.label || "";
        let url = widget.action.url || '';
        let uploadOpts = {
            maxFiles: 99,
            size: 50 * 1024 * 1024,
            maxFilesize: 50,
            acceptedFiles: "video/mp4"
        };
        let webVideoErrorNode = "";
        if (!this.state.is_valid_video_src){
            webVideoErrorNode = <div className='webErrorTips'>{this.state.errors}</div>
        }

        let videoInnerNode = "";
        if (currentTab == "local"){
            let replaceNode = "";
            if (html){
                replaceNode =
                    <span className="replace_audio">
                        {$._("Replace")}
                        <span>{label}</span>
                    </span>
            }
            videoInnerNode = <Upload ref="upload" prefix='eventVideo' options={uploadOpts} type={consts.WIDGET_TYPE.VIDEO} dialog={this} tips={url}/>
        } else {
            videoInnerNode =
                <div className="form-group video_web">
                    <div className="single-upload-group rightVideo">
                         <div className="default-status">
                            <input ref="htmlInput" onChange={(e) => this.handleOnHtmlChanged(e)} onBlur={() => this.handleOnInputBlur()} type="text" value={html} className="form-control" placeholder={$._('Please write online video address')} />
                         </div>
                     </div>
                    {webVideoErrorNode}
                </div>
        }

        return (
            <div className="play-video" id='eventVideo' ref= 'dialog'>
                <div className="play_title">
                    <div onClick={(e) => this.handleOnChangeVideoType(e)} name="local" className={"play_local " + (currentTab == "local" ? "activebtn" : "")}>{$._("Local video")}</div>
                    <div onClick={(e) => this.handleOnChangeVideoType(e)} name="web" className={"play_web " + (currentTab == "web" ? "activebtn" : "")}>{$._("Online video")}</div>
                </div>
                {videoInnerNode}
            </div>
        )
    }
};

const mapStateToProps = ({ editor, widgets}) => {
  const pageId = editor.selectedPageId;
  return {
      widget: editor.selectedWidget,
      widgets: widgets.filter(w => w.page_id === pageId),
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEventVideoInput);
